package com.corpdata.system.md.service.impl;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.corpdata.common.utils.CorpdataUtil;
import com.corpdata.system.md.dao.SMSRecordMapper;
import com.corpdata.system.md.entity.SMS;
import com.corpdata.system.md.entity.SMSRecord;
import com.corpdata.system.md.service.SMSMtService;

@Service
/**
 * 发送短信
 * 
 */
public class SMSMtServiceImpl implements SMSMtService{
	
	@Autowired
	private SMSRecordMapper smsRecordMapper;
	
	@Value("${sms.sn}")
	private String sn;
	@Value("${sms.password}")
	private String password;
	@Value("${sms.serviceURL}")
	private String serviceURL;
	@Value("${sms.registrationNotice}")
	private String registrationNotice;
	@Value("${sms.meetingRoomNotice.rentalStaff.successfulNotification}")
	private String rentalStaffSuccessfulNotification;
	@Value("${sms.meetingRoomNotice.rentalStaff.comingSoon}")
	private String rentalStaffComingSoon;
	@Value("${sms.meetingRoomNotice.tenant.successfulNotification}")
	private String tenantSuccessfulNotification;
	@Value("${sms.meetingRoomNotice.tenant.comingSoon}")
	private String tenantComingSoon;
	@Value("${sms.visitorReservation.visitor}")
	private String visitor;
	@Value("${sms.visitorReservation.rentalStaff}")
	private String rentalStaff;
	@Value("${sms.invitingVisitors.invitee}")
	private String invitingVisitorsInvitee;
	@Value("${sms.invitingVisitors.inviter}")
	private String invitingVisitorsInviter;
	@Value("${sms.meetingRoomNotice.cancelOrder.cancelNotification}")
	private String cancelOrder;
	/**
	 * 验证码
	 */
	public SMSRecord sendTheVerificationCode(String phoneNumber,String code){
		String template=registrationNotice;
		String content=template.replace("$number1$", code);
		SMSRecord result=SmsMt(phoneNumber,content);
		return result;
	}
	
	@Override
	public SMSRecord meetingRoomNoticeRentalPersonnelNotificationOfSuccess(String phoneNumber, String team,
			String building, String time) {
		String template=rentalStaffSuccessfulNotification;
		String content=template.replace("$number1$", team).replace("$number2$", building).replace("$number3$", time);
		SMSRecord result=SmsMt(phoneNumber,content);
		return result;
	}

	@Override
	public SMSRecord meetingRoomNoticeRentalStaffNoticeOfComingSoon(String phoneNumber
			,String team,String building,String hour) {
		String template=rentalStaffComingSoon;
		String content=template.replace("$number1$", team).replace("$number2$", building).replace("$number3$", hour);
		SMSRecord result=SmsMt(phoneNumber,content);
		return result;
	}

	@Override
	public SMSRecord meetingRoomNotificationTenantNotificationOfSuccess(String phoneNumber, String building, String time,
			String hour) {
		String template=tenantSuccessfulNotification;
		String content=template.replace("$number1$", building).replace("$number2$", time).replace("$number3$", hour);
		SMSRecord result=SmsMt(phoneNumber,content);
		return result;
	}

	@Override
	public SMSRecord MeetingRoomNotificationTenantNoticeOfComingSoon(String phoneNumber,
			String building, String hour,String phone) {
		String template=tenantComingSoon;
		String content=template.replace("$number1$", building).replace("$number2$", hour).replace("$number3$", phone);
		SMSRecord result=SmsMt(phoneNumber,content);
		return result;
	}

	@Override
	public SMSRecord visitorAppointmentVisitor(String phoneNumber, 
			String building, String project, String time,String phone) {
		String template=visitor;
		String content=template.replace("$number1$", building).replace("$number2$", project)
				.replace("$number3$", time).replace("$number4$", phone);
		SMSRecord result=SmsMt(phoneNumber,content);
		return result;
	}

	@Override
	public SMSRecord visitorAppointmentRentalStaff(String phoneNumber, String visitor, String time, String building,
			String project, String phone) {
		String template=rentalStaff;
		String content=template.replace("$number1$", visitor).replace("$number2$", time).replace("$number3$", building)
				.replace("$number4$", project).replace("$number5$", phone);
		SMSRecord result=SmsMt(phoneNumber,content);
		return result;
	}

	@Override
	public SMSRecord invitingVisitorsInvitees(String phoneNumber, String invitee, String time, String building,
			String project, String address) {
		String template=invitingVisitorsInvitee;
		System.out.println(template);
		String content=template.replace("$number1$", invitee).replace("$number2$", time).replace("$number3$", building)
				.replace("$number4$", project).replace("$number5$", address);
		SMSRecord result=SmsMt(phoneNumber,content);
		return result;
	}
	
	@Override
	public SMSRecord invitingVisitorsInviters(String phoneNumber, String visitor, String project, String phone,
			String wx) {
		String template=invitingVisitorsInviter;
		System.out.println(template);
		String content=template.replace("$number1$", visitor).replace("$number2$", project).replace("$number3$", phone)
				.replace("$number4$", wx);
		SMSRecord result=SmsMt(phoneNumber,content);
		return result;
	}
	

	@Override
	public SMSRecord cancelOrder(String phoneNumber, String date, String starTime, String endTime, String fieldName) {
		String template=cancelOrder;
		System.out.println(template);//【能加空间】您预订的[$number1$]使用时间为[$number2$，$number3$-$number4$]已取消。如有任何问题，请和管理员联系
		String content=template.replace("$number1$", fieldName).replace("$number2$", date).replace("$number3$", starTime)
				.replace("$number4$", endTime);
		SMSRecord result=SmsMt(phoneNumber,content);
		return result;
	}
	/**
	 * 发送短信 
	 * @param phoneNumber 手机号
	 * @param content 内容
	 * @return
	 */
	public SMSRecord SmsMt(String phoneNumber,String content){
		//输入软件序列号和密码
		SMS client;
		String result="";
		boolean is=false;
		try {
			client = new SMS();
			client.setPassword(password);
			client.setSn(sn);
			client.setServiceURL(serviceURL);
			client.setPwd(getMD5(sn + password));
			//我们的Demo最后是拼成xml了，所以要按照xml的语法来转义
			if(content.indexOf("&")>=0) {
				content=content.replace("&","&amp;");
			}
			if(content.indexOf("<")>=0) {
				content=content.replace("<","&lt;");
			}
			if(content.indexOf(">")>=0) {
				content=	content.replace(">","&gt;");
			}
			//短信发送
			String result_mt = client.mt(phoneNumber, content, "", "", "");
			if(result_mt.startsWith("-")||result_mt.equals("")){//以负号判断是否发送成功
//				result="发送失败！返回值为："+result_mt+"。请查看webservice返回值对照表";
				result=result_mt;
			}else{//输出返回标识，为小于19位的正数，String类型的，记录您发送的批次
//				result="发送成功，返回值为："+result_mt;
				result=result_mt;
				is=true;
			}
		} catch (UnsupportedEncodingException e) {
			System.out.print("短信发送出错！");
			e.printStackTrace();
		}
//		String jsonStr = "{\"success\":"+is+",\"msg\":\""+result+"\"}";
		SMSRecord smsRecord =createdSMSRocord(phoneNumber,is,result,content);
		return smsRecord;
	}
	
	/*
	 * 方法名称：register 
	 * 功    能：注册 
	 * 参    数：对应参数 省份，城市，行业，企业名称，联系人，电话，手机，电子邮箱，传真，地址，邮编 
	 * 返 回 值：注册结果（String）
	public String register(String province, String city, String trade,
			String entname, String linkman, String phone, String mobile,
			String email, String fax, String address, String postcode,String sign) {
		String result = "";
		String soapAction = "http://tempuri.org/Register";
		String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
		xml += "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">";
		xml += "<soap12:Body>";
		xml += "<Register xmlns=\"http://tempuri.org/\">";
		xml += "<sn>" + sn + "</sn>";
		xml += "<pwd>" + password + "</pwd>";
		xml += "<province>" + province + "</province>";
		xml += "<city>" + city + "</city>";
		xml += "<trade>" + trade + "</trade>";
		xml += "<entname>" + entname + "</entname>";
		xml += "<linkman>" + linkman + "</linkman>";
		xml += "<phone>" + phone + "</phone>";
		xml += "<mobile>" + mobile + "</mobile>";
		xml += "<email>" + email + "</email>";
		xml += "<fax>" + fax + "</fax>";
		xml += "<address>" + address + "</address>";
		xml += "<postcode>" + postcode + "</postcode>";
		xml += "<sign></sign>";
		xml += "</Register>";
		xml += "</soap12:Body>";
		xml += "</soap12:Envelope>";

		URL url;
		try {
			url = new URL(serviceURL);

			URLConnection connection = url.openConnection();
			HttpURLConnection httpconn = (HttpURLConnection) connection;
			ByteArrayOutputStream bout = new ByteArrayOutputStream();
			bout.write(xml.getBytes());
			//bout.write(xml.getBytes("GBK"));
			byte[] b = bout.toByteArray();
			httpconn.setRequestProperty("Content-Length", String
					.valueOf(b.length));
			httpconn.setRequestProperty("Content-Type",
					"text/xml; charset=gb2312");
			httpconn.setRequestProperty("SOAPAction", soapAction);
			httpconn.setRequestMethod("POST");
			httpconn.setDoInput(true);
			httpconn.setDoOutput(true);

			OutputStream out = httpconn.getOutputStream();
			out.write(b);
			out.close();

			InputStreamReader isr = new InputStreamReader(httpconn
					.getInputStream());
			BufferedReader in = new BufferedReader(isr);
			String inputLine;
			while (null != (inputLine = in.readLine())) {
				Pattern pattern = Pattern
						.compile("<RegisterResult>(.*)</RegisterResult>");
				Matcher matcher = pattern.matcher(inputLine);
				while (matcher.find()) {
					result = matcher.group(1);
				}
			}
			in.close();
			return new String(result.getBytes(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}*/
	
	/*
	 * 方法名称：getMD5 
	 * 功    能：字符串MD5加密 
	 * 参    数：待转换字符串 
	 * 返 回 值：加密之后字符串
	 */
	public String getMD5(String sourceStr) throws UnsupportedEncodingException {
		String resultStr = "";
		try {
			byte[] temp = sourceStr.getBytes();
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(temp);
			// resultStr = new String(md5.digest());
			byte[] b = md5.digest();
			for (int i = 0; i < b.length; i++) {
				char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
						'9', 'A', 'B', 'C', 'D', 'E', 'F' };
				char[] ob = new char[2];
				ob[0] = digit[(b[i] >>> 4) & 0X0F];
				ob[1] = digit[b[i] & 0X0F];
				resultStr += new String(ob);
			}
			return resultStr;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/*
	 * 方法名称：chargeFee 
	 * 功    能：充值 
	 * 参    数：充值卡号，充值密码 
	 * 返 回 值：操作结果（String）
	 */
	public String chargeFee(String cardno, String cardpwd) {
		String result = "";
		String soapAction = "http://tempuri.org/ChargUp";
		String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
		xml += "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">";
		xml += "<soap12:Body>";
		xml += "<ChargUp xmlns=\"http://tempuri.org/\">";
		xml += "<sn>" + sn + "</sn>";
		xml += "<pwd>" + password + "</pwd>";
		xml += "<cardno>" + cardno + "</cardno>";
		xml += "<cardpwd>" + cardpwd + "</cardpwd>";
		xml += "</ChargUp>";
		xml += "</soap12:Body>";
		xml += "</soap12:Envelope>";

		URL url;
		try {
			url = new URL(serviceURL);

			URLConnection connection = url.openConnection();
			HttpURLConnection httpconn = (HttpURLConnection) connection;
			ByteArrayOutputStream bout = new ByteArrayOutputStream();
			bout.write(xml.getBytes());
			byte[] b = bout.toByteArray();
			httpconn.setRequestProperty("Content-Length", String
					.valueOf(b.length));
			httpconn.setRequestProperty("Content-Type",
					"text/xml; charset=gb2312");
			httpconn.setRequestProperty("SOAPAction", soapAction);
			httpconn.setRequestMethod("POST");
			httpconn.setDoInput(true);
			httpconn.setDoOutput(true);

			OutputStream out = httpconn.getOutputStream();
			out.write(b);
			out.close();

			InputStreamReader isr = new InputStreamReader(httpconn
					.getInputStream());
			BufferedReader in = new BufferedReader(isr);
			String inputLine;
			while (null != (inputLine = in.readLine())) {
				Pattern pattern = Pattern
						.compile("<ChargUpResult>(.*)</ChargUpResult>");
				Matcher matcher = pattern.matcher(inputLine);
				while (matcher.find()) {
					result = matcher.group(1);
				}
			}
			in.close();
			// return result;
			return new String(result.getBytes(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
	/*
	 * 方法名称：getBalance 
	 * 功    能：获取余额 
	 * 参    数：无 
	 * 返 回 值：余额（String）
	public String getBalance() {
		String result = "";
		String soapAction = "http://tempuri.org/balance";
		String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
		xml += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
		xml += "<soap:Body>";
		xml += "<balance xmlns=\"http://tempuri.org/\">";
		xml += "<sn>" + sn + "</sn>";
		xml += "<pwd>" + pwd + "</pwd>";
		xml += "</balance>";
		xml += "</soap:Body>";
		xml += "</soap:Envelope>";

		URL url;
		try {
			url = new URL(serviceURL);

			URLConnection connection = url.openConnection();
			HttpURLConnection httpconn = (HttpURLConnection) connection;
			ByteArrayOutputStream bout = new ByteArrayOutputStream();
			bout.write(xml.getBytes());
			byte[] b = bout.toByteArray();
			httpconn.setRequestProperty("Content-Length", String
					.valueOf(b.length));
			httpconn.setRequestProperty("Content-Type",
					"text/xml; charset=gb2312");
			httpconn.setRequestProperty("SOAPAction", soapAction);
			httpconn.setRequestMethod("POST");
			httpconn.setDoInput(true);
			httpconn.setDoOutput(true);

			OutputStream out = httpconn.getOutputStream();
			out.write(b);
			out.close();

			InputStreamReader isr = new InputStreamReader(httpconn
					.getInputStream());
			BufferedReader in = new BufferedReader(isr);
			String inputLine;
			while (null != (inputLine = in.readLine())) {
				Pattern pattern = Pattern
						.compile("<balanceResult>(.*)</balanceResult>");
				Matcher matcher = pattern.matcher(inputLine);
				while (matcher.find()) {
					result = matcher.group(1);
				}
			}
			in.close();
			return new String(result.getBytes());
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}*/
	
	/**
	 * 发送短信日志
	 * @param phoneNumber
	 * @param status
	 * @param returnCode
	 * @param content
	 */
	public SMSRecord createdSMSRocord(String phoneNumber,boolean status,String returnCode,String content){
		SMSRecord record=new SMSRecord();
		Date now=new Date();
		record.setId(CorpdataUtil.getUUID());
		record.setCreatedTime(now);
		record.setLastModified(now);
		record.setPhoneNumber(phoneNumber);
		record.setStatus(status);
		record.setReturnCode(returnCode);
		record.setContent(content);
		smsRecordMapper.insertSMSRecord(record);
		return record;
	}


}
